package dao

import (
	"fmt"
	"github.com/google/uuid"
	"smart-health-platforms/config"
	"smart-health-platforms/pkg"
	"smart-health-platforms/untils"
	"strconv"
	"time"
	"user_srv/model"
	"user_srv/user"
)

// 权限添加
func MemberDisplay() []*user.MemberCenter {
	var membershipBenefits model.MembershipBenefits
	display, err := membershipBenefits.MemberDisplay()
	if err != nil {
		return nil
	}
	var list []*user.MemberCenter
	for _, v := range display {
		list = append(list, &user.MemberCenter{
			Name:        v.Name,
			Grade:       v.Grade,
			Description: v.Description,
			Benefits:    v.Benefits,
		})
	}
	return list
}

// 权限添加
func MembershipLevelDetail() []*user.MemberCenter {
	var membershipBenefits model.MembershipBenefits
	display, err := membershipBenefits.MemberDisplay()
	if err != nil {
		pkg.Warn("会员等级详情失败")
		return nil
	}
	var list []*user.MemberCenter
	for _, v := range display {
		list = append(list, &user.MemberCenter{
			Name:        v.Name,
			Grade:       v.Grade,
			Description: v.Description,
			Benefits:    v.Benefits,
		})
	}
	return list
}

// 会员等级添加
func MembershipLevelAdd(Name string, Grade int32, Description string) {
	var membershipLevels model.MembershipLevels
	membershipLevels.Name = Name
	membershipLevels.Grade = Grade
	membershipLevels.Description = Description
	if err := membershipLevels.CreateMembershipLevel(); err != nil {
		pkg.Warn("会员等级添加失败")
		return
	}
	pkg.Info("会员等级添加成功")
}

// 会员等级展示
func MembershipLevelList() []*user.MembershipLevelList {
	var membershipLevels model.MembershipLevels
	level, err := membershipLevels.GetMembershipLevel()
	if err != nil {
		pkg.Warn("会员等级展示失败")
		return nil
	}
	var resp []*user.MembershipLevelList
	for _, item := range level {
		resp = append(resp, &user.MembershipLevelList{
			Name:        item.Name,
			Grade:       item.Grade,
			Description: item.Description,
		})
	}
	return resp
}

// 会员等级更新
func MembershipLevelUpdate(Id int32, Name string, Grade int32, Description string) {
	var membershipLevels model.MembershipLevels
	membershipLevels.Id = Id
	membershipLevels.Name = Name
	membershipLevels.Grade = Grade
	membershipLevels.Description = Description
	if err := membershipLevels.UpdateMembershipLevel(); err != nil {
		pkg.Warn("会员等级更新失败")
		return
	}
	pkg.Info("会员等级更新成功")
}

// 会员等级删除
func MembershipLevelDel(Id int32) {
	var membershipLevels model.MembershipLevels
	membershipLevels.Id = Id
	if err := membershipLevels.DeleteMembershipLevel(); err != nil {
		pkg.Warn("会员等级删除失败")
		return
	}
	pkg.Info("会员等级删除成功")
}

// 会员续费
func MembershipRenewal(Price int64) (string, string) {
	var membershipRenewals model.MembershipRenewals                                                 // 会员续费记录表
	membershipRenewals.OrderNumber = "HY" + fmt.Sprintf("%v", time.Now().Unix()) + uuid.NewString() // 订单号
	membershipRenewals.UserId = 1                                                                   // 用户uid
	membershipRenewals.RenewalDate = int32(time.Now().Unix())                                       // 续费日期
	membershipRenewals.Amount = uint64(Price)                                                       // 金额
	membershipRenewals.PaymentMethod = 1                                                            // 支付方式
	var memberUserLevel model.MemberUserLevel                                                       // 会员等级表
	memberUserLevel.UserId = 1                                                                      // 用户uid
	var num int32                                                                                   // 积分
	var num1 int32                                                                                  // 到期日期
	if Price == 30 {
		num1 = 30 * 24 * 60 * 60
		num = 150
	} else if Price == 80 {
		num1 = 90 * 24 * 60 * 60
		num = 280
	} else if Price == 150 {
		num1 = 180 * 24 * 60 * 60
		num = 350
	} else if Price == 280 {
		num1 = 365 * 24 * 60 * 60
		num = 500
	} else {
		return "", ""
	}
	membershipRenewals.ExpireDate = num1 // 到期日期

	if err := memberUserLevel.PointsIncrease(num); err != nil { // 积分增加
		return "", ""
	}
	if err := memberUserLevel.UpdateMemberUserLevel(int(num1)); err != nil { // 到期日期增加
		return "", ""
	}
	if err := membershipRenewals.CreateMembershipRenewals(); err != nil { // 会员续费记录表增加
		return "", ""
	}
	alipay := untils.MAliPay{}                                                                              // 支付宝
	pay := alipay.AliPay(membershipRenewals.OrderNumber, strconv.FormatUint(membershipRenewals.Amount, 10)) // 支付宝支付

	return membershipRenewals.OrderNumber, pay
}

// 会员状态更新
func MemberStatusUpdate(OrderSn string, Status int64) {
	var membershipRenewals model.MembershipRenewals
	membershipRenewals.OrderNumber = OrderSn
	membershipRenewals.Status = uint8(Status)
	if err := membershipRenewals.UpdateMembershipRenewals(); err != nil {
		return
	}
	var memberUserLevel model.MemberUserLevel
	if err := membershipRenewals.GetMembershipRenewals(); err != nil {
		return
	}
	var num int32  // 积分
	var num1 int32 // 到期日期
	if membershipRenewals.Amount == 30 {
		num1 = 30 * 24 * 60 * 60
		num = 150
	} else if membershipRenewals.Amount == 80 {
		num1 = 90 * 24 * 60 * 60
		num = 280
	} else if membershipRenewals.Amount == 150 {
		num1 = 180 * 24 * 60 * 60
		num = 350
	} else if membershipRenewals.Amount == 280 {
		num1 = 365 * 24 * 60 * 60
		num = 500
	} else {
		return
	}
	membershipRenewals.ExpireDate = num1 // 到期日期

	if err := memberUserLevel.PointsIncrease(num); err != nil { // 积分增加
		return
	}
	if err := memberUserLevel.UpdateMemberUserLevel(int(num1)); err != nil { // 到期日期增加
		return
	}
	if err := memberUserLevel.GetUserLevel(); err != nil {
		return
	}
	var num3 int                                                        // 会员等级
	if memberUserLevel.Points > 1000 && memberUserLevel.Points < 3000 { // 1000-3000
		num3 = 2
	} else if memberUserLevel.Points > 3000 && memberUserLevel.Points < 5000 { // 3000-5000
		num3 = 3
	} else if memberUserLevel.Points > 5000 && memberUserLevel.Points < 8000 { // 5000-8000
		num3 = 4
	} else if memberUserLevel.Points > 8000 && memberUserLevel.Points < 10000 { // 8000-10000
		num3 = 5
	} else if memberUserLevel.Points > 10000 { // 10000以上
		num3 = 6
	}
	if err := memberUserLevel.ModifyMembershipLevel(num3); err != nil { // 会员等级修改
		return
	}
	if err := membershipRenewals.UpdateMembershipRenewals(); err != nil {
		return
	}

}

// 会员等级展示
func MembershipUserList() []*user.MembershipUserList {
	var memberUserLevel model.MemberUserLevel
	list, err := memberUserLevel.MemberUserList()
	if err != nil {
		return nil
	}
	var resp []*user.MembershipUserList
	for _, userList := range list {
		resp = append(resp, &user.MembershipUserList{
			NickName: userList.NickName,
			ImageCur: userList.ImageCur,
			Age:      userList.Age,
			Name:     userList.Name,
			Grade:    userList.Grade,
		})
	}
	return resp
}

// 会员等级详情
func MemberDetails(Id int32) model.Membership {
	var membershipBenefits model.MembershipBenefits
	membershipBenefits.LevelId = uint64(Id)
	details, err := membershipBenefits.MemberDetails()
	if err != nil {
		pkg.Warn("会员等级详情失败")
		return model.Membership{}
	}
	return details
}

// 会员等级详情
func EquityIncrease(LevelId int32, Benefits string) error {
	var membershipBenefits model.MembershipBenefits
	membershipBenefits.LevelId = uint64(LevelId)
	membershipBenefits.Benefits = Benefits
	if err := membershipBenefits.Create(); err != nil {
		return err
	}
	return nil
}

// 会员等级详情
func RightsCollection(BenefitsId int32) error {
	var memberBenefitClaims model.MemberBenefitClaims
	memberBenefitClaims.UserId = 1
	memberBenefitClaims.BenefitId = uint32(BenefitsId)
	var memberUserLevel model.MemberUserLevel
	memberUserLevel.UserId = 1
	err := memberUserLevel.GetUserLevel()
	if err != nil {
		return nil
	}
	if BenefitsId > memberUserLevel.LevelId {
		pkg.Warn("用户等级不足")
		return nil
	}

	// 检查用户是否在本月已领取过该权益
	now := time.Now()
	startOfMonth := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location()) // 本月第一天
	endOfMonth := startOfMonth.AddDate(0, 1, 0).Add(-time.Second)                     // 本月最后一天

	var count int64
	result := config.DB.Model(&model.MemberBenefitClaims{}).
		Where("user_id = ? AND benefit_id = ? AND created_at BETWEEN ? AND ?",
			memberBenefitClaims.UserId, memberBenefitClaims.BenefitId, startOfMonth, endOfMonth).
		Count(&count)
	if result.Error != nil {
		pkg.Warn("查询领取记录失败")
		return result.Error
	}

	if count > 0 {
		pkg.Warn("本月已领取过该权益")
		return nil
	}

	// 领取权益
	if err = memberBenefitClaims.CreateBenefit(); err != nil {
		pkg.Warn("权益领取失败")
		return err
	}

	pkg.Info("权益领取成功")
	return nil
}
